package com.wbl.tijiancms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wbl.tijiancms.mapper.HospitalMapper;
import com.wbl.tijiancms.mapper.OrdersMapper;
import com.wbl.tijiancms.pojo.Hospital;
import com.wbl.tijiancms.service.CalendarService;
import com.wbl.tijiancms.vo.CalendarRequestDto;
import com.wbl.tijiancms.vo.CalendarResponseDto;
import com.wbl.tijiancms.vo.OrdersMapperDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public class CalendarServiceImpl implements CalendarService {

    @Autowired
    private HospitalMapper hospitalMapper;
    @Autowired
    private OrdersMapper ordersMapper;

    @Override
    public List<CalendarResponseDto> getCalendarList30(CalendarRequestDto calendarRequestDto){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();

        //做一个临时集合，作为去Orders表中查询的参数
        List<OrdersMapperDto> parameList = new ArrayList<>();
        for(int i=0;i<30;i++) {
            OrdersMapperDto dto = new OrdersMapperDto();
            calendar.add(Calendar.DATE, 1); //计算1天后的时间
            dto.setDate(sdf.format(calendar.getTime()));
            dto.setHpId(calendarRequestDto.getHpId());
            parameList.add(dto);
        }

        //根据parameList参数，查询30天预约日期中，每一天的已预约人数
        //查询结果CalendarResponseDto中只有两个属性：ymd、existing，还有两个属性需要填充：total、remainder
        List<CalendarResponseDto> calendarList30 = ordersMapper.listOrdersAppointmentNumber(parameList);

        //根据医院编号，获取预约规则，就能获取每天最多预约人数
        QueryWrapper<Hospital> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("hpId",calendarRequestDto.getHpId());
        String[] strArr = hospitalMapper.selectOne(queryWrapper).getRule().split(",");


        //继续填充calendarList30返回值中的total、remainder属性
        for(CalendarResponseDto cd : calendarList30) {
            //将预约日期转换为Calendar对象
            try {
                calendar.setTime(sdf.parse(cd.getYmd()));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            //通过Calendar对象的get方法获取某天为星期几，就可以通过预约规则数组获取某天的总预约人数
            int total = Integer.parseInt(strArr[calendar.get(Calendar.DAY_OF_WEEK)-1]);
            //填充total属性
            cd.setTotal(total);
            //填充remainder属性
            cd.setRemainder(total-cd.getExisting());
        }

        return calendarList30;
    }
}
